<template>
  <div>
    <div class="flex flex-col items-center justify-center w-full gap-3 mt-3">
      <h3 class="scroll-m-20 text-2xl font-semibold tracking-tight upload-txt">批量阅读</h3>
      <p class="text-sm upload-txt">从几十篇文献中批量获取核心数据、方法、结论等信息</p>
    </div>
    <div class="upload-parent">
      <div class="flex flex-col gap-2">
        <div :class="dialogPage ? '' : 'reading-page'" v-loading="loading" :element-loading-text="loadingTxt">
          <div class="relative">
            <div v-if="fileList.length === 0">
              <el-upload
                style="width: 100%"
                class="upload-demo"
                drag
                :show-file-list="false"
                multiple
                :on-change="handleMainFileChange"
                :auto-upload="false"
                :accept="'.pdf,'"
              >
                <div style="display: inline-block">
                  <svg xmlns="http://www.w3.org/2000/svg" width="126" height="96" fill="none" viewBox="0 0 126 96"><g filter="url(#filter0_d_48259_24903)"><rect width="45.672" height="61.719" x="11.145" y="22.624" fill="#fff" rx="6" transform="rotate(-12 11.145 22.624)"></rect><rect width="44.872" height="60.919" x="11.619" y="22.932" stroke="#E4E9EC" stroke-width="0.8" rx="5.6" transform="rotate(-12 11.619 22.932)"></rect></g><rect width="24.151" height="2.683" x="24.536" y="34.015" fill="#D2DBDF" rx="1.342" transform="rotate(-12 24.536 34.015)"></rect><rect width="24.151" height="2.683" x="26.211" y="41.889" fill="#D2DBDF" rx="1.342" transform="rotate(-12 26.21 41.889)"></rect><rect width="24.151" height="2.683" x="27.887" y="49.764" fill="#D2DBDF" rx="1.342" transform="rotate(-12 27.887 49.764)"></rect><rect width="16.101" height="2.683" x="33.501" y="56.802" fill="#D2DBDF" rx="1.342" transform="rotate(-12 33.501 56.802)"></rect><g filter="url(#filter1_d_48259_24903)"><rect width="45.672" height="61.719" x="70.181" y="13.134" fill="#fff" rx="6" transform="rotate(12 70.18 13.134)"></rect><rect width="44.872" height="60.919" x="70.489" y="13.608" stroke="#E4E9EC" stroke-width="0.8" rx="5.6" transform="rotate(12 70.489 13.608)"></rect></g><rect width="24.151" height="2.683" x="77.784" y="28.984" fill="#D2DBDF" rx="1.342" transform="rotate(12 77.784 28.984)"></rect><rect width="24.151" height="2.683" x="76.109" y="36.859" fill="#D2DBDF" rx="1.342" transform="rotate(12 76.11 36.86)"></rect><rect width="24.151" height="2.683" x="74.442" y="44.733" fill="#D2DBDF" rx="1.342" transform="rotate(12 74.442 44.733)"></rect><rect width="16.101" height="2.683" x="76.703" y="53.446" fill="#D2DBDF" rx="1.342" transform="rotate(12 76.703 53.446)"></rect><g filter="url(#filter2_d_48259_24903)"><path fill="#E4E9EC" stroke="#D2DBDF" stroke-linejoin="round" stroke-width="0.8" d="M69.1 30.674V11.001l19.063 19.804-19.062-.13z"></path><path fill="#fff" stroke="#D2DBDF" stroke-width="0.8" d="M44.3 11.275c-2.332.67-4.153 2.138-5.306 4.316-1.1 2.059-1.009-.761-1.009 28.985 0 25.3.013 26.467.236 27.214.878 2.86 3.079 5.142 5.79 6.007l.918.289h36.29l.917-.289c2.699-.852 4.913-3.16 5.79-6.007.223-.747.236-1.744.236-20.919V30.804l-9.524-.104-9.538-.027V11l-11.948.013c-11.437 0-12 .013-12.852.262z"></path><path fill="#647A84" d="M47.38 59.427V47.352h4.988c.904 0 1.684.176 2.34.53.661.35 1.17.84 1.528 1.468.358.625.537 1.353.537 2.182 0 .833-.183 1.563-.549 2.188a3.678 3.678 0 01-1.55 1.444c-.673.342-1.47.513-2.394.513h-3.078v-2.3h2.535c.44 0 .808-.076 1.103-.23.298-.153.524-.367.678-.642.153-.28.23-.604.23-.973 0-.373-.077-.696-.23-.967a1.544 1.544 0 00-.678-.637c-.299-.15-.667-.224-1.103-.224h-1.439v9.723H47.38zM62.741 59.427h-4.463V47.352h4.457c1.23 0 2.29.241 3.178.725a4.957 4.957 0 012.064 2.075c.483.9.725 1.977.725 3.231 0 1.258-.242 2.34-.725 3.243a4.957 4.957 0 01-2.058 2.082c-.892.48-1.951.719-3.178.719zm-1.545-2.488h1.433c.676 0 1.248-.114 1.716-.342.472-.232.827-.608 1.067-1.126.244-.523.366-1.219.366-2.088 0-.868-.122-1.56-.366-2.075-.244-.519-.603-.892-1.079-1.12-.472-.232-1.053-.348-1.745-.348h-1.392v7.099zM70.473 59.427V47.352h8.243v2.37H73.39v2.476h4.8v2.376h-4.8v4.853h-2.918z"></path></g><defs><filter id="filter0_d_48259_24903" width="79.275" height="91.636" x="0.26" y="4.243" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"></feFlood><feColorMatrix in="SourceAlpha" result="hardAlpha" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"></feColorMatrix><feOffset dy="2"></feOffset><feGaussianBlur stdDeviation="6"></feGaussianBlur><feComposite in2="hardAlpha" operator="out"></feComposite><feColorMatrix values="0 0 0 0 0.823529 0 0 0 0 0.858824 0 0 0 0 0.87451 0 0 0 0.7 0"></feColorMatrix><feBlend in2="BackgroundImageFix" result="effect1_dropShadow_48259_24903"></feBlend><feBlend in="SourceGraphic" in2="effect1_dropShadow_48259_24903" result="shape"></feBlend></filter><filter id="filter1_d_48259_24903" width="79.275" height="91.636" x="46.464" y="4.249" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"></feFlood><feColorMatrix in="SourceAlpha" result="hardAlpha" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"></feColorMatrix><feOffset dy="2"></feOffset><feGaussianBlur stdDeviation="6"></feGaussianBlur><feComposite in2="hardAlpha" operator="out"></feComposite><feColorMatrix values="0 0 0 0 0.823529 0 0 0 0 0.858824 0 0 0 0 0.87451 0 0 0 0.7 0"></feColorMatrix><feBlend in2="BackgroundImageFix" result="effect1_dropShadow_48259_24903"></feBlend><feBlend in="SourceGraphic" in2="effect1_dropShadow_48259_24903" result="shape"></feBlend></filter><filter id="filter2_d_48259_24903" width="74.98" height="91.887" x="25.583" y="0.6" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"></feFlood><feColorMatrix in="SourceAlpha" result="hardAlpha" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0"></feColorMatrix><feOffset dy="2"></feOffset><feGaussianBlur stdDeviation="6"></feGaussianBlur><feComposite in2="hardAlpha" operator="out"></feComposite><feColorMatrix values="0 0 0 0 0.823529 0 0 0 0 0.858824 0 0 0 0 0.87451 0 0 0 0.7 0"></feColorMatrix><feBlend in2="BackgroundImageFix" result="effect1_dropShadow_48259_24903"></feBlend><feBlend in="SourceGraphic" in2="effect1_dropShadow_48259_24903" result="shape"></feBlend></filter></defs></svg>
                </div>
                <div class="el-upload__text">
                  <p class="mb-1.5 text-md font-medium upload-txt">将文件拖放到此处，或点击选择文件</p>
                  <p class="upload-txt text-xs">最多{{fileLimit}}个文件，最大50MB</p>
                </div>
                <div style="margin-top: 10px">
                  <el-button class="upload-btn">
                    <el-icon style="margin-right: 10px"><Upload /></el-icon>
                    选择文件
                  </el-button>
                </div>
                <template #tip>
                  <div class="el-upload__tip upload-txt" style="text-align: center; margin-top: 20px">
                    文件解析可能需要三分钟左右。暂不支持扫描件识别。
                  </div>
                </template>
              </el-upload>
            </div>
            <div v-else>
              <div style="overflow: hidden">
                <div class="file-total">文件 ({{fileList.length}})</div>
                <div class="file-operate">
                  <el-upload
                    class="upload-table"
                    :show-file-list="false"
                    multiple
                    :on-change="handleMainFileChange"
                    :auto-upload="false"
                    :accept="'.pdf,'"
                  >
                    <el-button class="operate-btn">
                      <el-icon style="margin-right: 5px"><Upload /></el-icon>
                      添加文件
                    </el-button>
                  </el-upload>
                  
                  <el-button class="operate-btn" @click="deleteAll">
                    <el-icon style="margin-right: 5px"><Delete /></el-icon>
                    全部移除
                  </el-button>
                  <el-select class="model-select" v-model="optionsVal" placeholder="请选择模式">
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                  <el-button class="operate-btn submit-btn" @click="submitCheck">
                    <el-icon style="margin-right: 5px"><Check /></el-icon>
                    开始解析
                  </el-button>
                </div>
              </div>
              <div class="table-content">
                <el-table :data="fileList" style="width: 100%" max-height='253'>
                  <el-table-column prop="name" label="文件名" />
                  <el-table-column prop="type" label="类型" width="100">
                    <template #default>
                      <span>PDF</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="size" label="大小" width="200">
                    <template #default="scope">
                      <span>{{sizeRender(scope.row.size)}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="60">
                    <template #default="scope">
                      <el-button
                        link
                        type="primary"
                        size="small"
                        @click.prevent="deleteRow(scope.$index)"
                      >
                        <el-icon size="18"><Delete /></el-icon>
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div class="el-upload__tip upload-txt" style="text-align: center; margin-top: 20px">
                文件解析可能需要三分钟左右。暂不支持扫描件识别。
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
  import { useRouter } from 'vue-router'
  import { watch, ref, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import { analyzeMultiple, fileCheck } from '@/api/user'
  // 引入pdfjs
  import * as pdfjsLib from 'pdfjs-dist'

  // 设置 PDF.js workerSrc 使用 import.meta.url 确保正确加载
  pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
    'pdfjs-dist/build/pdf.worker.mjs',
    import.meta.url
  ).toString()
  
  const props = defineProps(['dialogPage']) 
  const router = useRouter()

  const loading = ref(false);
  
  const options = ref([
    {
      value: 0,
      label: '速读模式：1积分/页'
    },
    {
      value: 1,
      label: '精读模式：5积分/页'
    },
    {
      value: 2,
      label: '研读模式：10积分/页'
    }
  ]);

  const optionsVal = ref(0);

  const maxSize = ref(50);  // 最大50M
  const fileLimit = ref(30);
  const fileList = ref([]);
  const fileName = ref(null);
  const fileValue = ref(null);
  const filePage = ref(0);
  const fileCount = ref(0);

  const loadingTxt = ref('');

  const handleMainFileChange = (file) => {
    if (file.size > maxSize.value * 1024 * 1024) {
      ElMessage.warning(`${file.name}大于${maxSize.value}M，请重新选择`)
    } else {
      const index = fileList.value.findIndex(item => item.name === file.name)
      if (index === -1 && fileList.value.length < fileLimit.value) {
        fileList.value.push(file);
      } else if (index === -1 && fileList.value.length >= fileLimit.value) {
        ElMessage.warning(`最多可选择 ${fileLimit.value} 个文件`)
      }
    }
  }

  const fileUploading = (evt, file, files) => {
    console.log(evt);
    console.log(file);
    console.log(files);
  }

  const deleteRow = (index) => {
    console.log(index);
    fileList.value.splice(index, 1);
  }

  const deleteAll = () => {
    fileList.value = [];
  }

  const sizeRender = (size) => {
    let newSize = 0;
    if (size < 1024) {
      newSize = `${size.toFixed(2)}B`;
    } else if (size >= 1024 && size < 1048576) {
      newSize = `${(size / 1024).toFixed(2)}KB`;
    } else if (size >= 1048576 && size < 1048576 * 1024) {
      newSize = `${(size / 1024 / 1024).toFixed(2)}M`;
    }
    return newSize;
  }

  // 使用标准的 pdfjs 方法，利用已配置的 workerSrc
  const getPdfPageCount = (file, index) => {
    console.log('开始处理文件:', file.name)
    
    // 先尝试直接显示一个alert确认函数被调用
    // alert('文件已选择，正在分析页数...')
    
    try {
      // 创建文件读取器
      const fileReader = new FileReader()
      
      fileReader.onload = function(event) {
        console.log('文件读取完成')
        try {
          // 尝试使用标准方法获取页数
          const data = event.target.result
          
          // 使用已配置的workerSrc解析PDF
          const loadingTask = pdfjsLib.getDocument({
            data: new Uint8Array(data)
          });
          
          loadingTask.promise.then(function(pdf) {
            // console.log('PDF解析成功')
            const pageCount = pdf.numPages
            // console.log('PDF页数:', pageCount)
            // 显示页数
            filePage.value += pageCount;
            fileCount.value += 1;
            // 计算页码进度占总进度5%
            const progressNum = Math.floor((fileCount.value / fileList.value.length) * 5 );
            // console.log(progressNum);
            loadingTxt.value = `正在解析 ${progressNum}%`;
            if (fileCount.value === fileList.value.length) {
              submitBtn();
              loadingTxt.value = `正在解析 5%`;
            }
            // console.log('fileCount', fileCount.value);
            // console.log(filePage.value);
            // alert(`上传的PDF文件共有 ${pageCount} 页`)
          }).catch(function(error) {
            loading.value = false;
            console.error('PDF解析错误:', error)
            ElMessage.error('解析PDF文件失败，请尝试其他文件');
          })
        } catch (error) {
          loading.value = false;
          console.error('处理文件内容失败:', error)
          ElMessage.error('处理文件内容失败: ' + error.message)
        }
      }
      
      fileReader.onerror = function() {
        loading.value = false;
        console.error('文件读取失败')
        ElMessage.error('文件读取失败')
      }
      
      // 开始读取文件
      console.log('开始读取文件内容')
      fileReader.readAsArrayBuffer(file)
    } catch (error) {
      loading.value = false;
      console.error('获取PDF页数失败:', error)
      ElMessage.error('获取PDF页数失败: ' + error.message)
    }
  }

  const submitCheck = () => {
    loading.value = true;
    loadingTxt.value = `正在解析`;
    filePage.value = 0;
    fileList.value.forEach((item, index) => {
      getPdfPageCount(item.raw, index);
    });
    // console.log(filePage.value);
  }
  const config = {
    onUploadProgress: function (e) {
      // console.log(e.progress);
      if (e.progress.toFixed(2) < 1) {
        // 准备文件进度占总进度95%
        const progressTxt = 5 + Math.floor(e.progress.toFixed(2) * 95);
        loadingTxt.value = `正在解析 ${progressTxt}%`;
      } else {
        loadingTxt.value = '正在上传，请稍等...'
      }
    }
  }
  const submitBtn = async ()=>{
    if (!filePage.value) {
      loading.value = false;
      ElMessage.error('文件解析失败，请重新选择');
      return false;
    }
    const params = {
      pages: filePage.value,
      modelType: optionsVal.value
    };
    let res = await fileCheck(params)
    if(res.code == 200 && res.data){
      console.log('积分够');
    } else {
      loading.value = false;
      ElMessage.error('积分不够，请先充值');
      return false;
    }
    try {
      // console.log(fileList.value);
      let formData = new FormData();
      fileList.value.forEach((item, index) => {
        formData.append('files', item.raw);
      });
      formData.append('modelType', optionsVal.value);
      const param = {params: formData, config};
      let res = await analyzeMultiple(param)
      if(res.code == 200){
          loading.value = false
          router.push('/record')
      } else {
        loading.value = false
        ElMessage.error(res.message);
      }
    } catch (error) {
      loading.value = false;
      ElMessage.error(error);
    }
  }
</script>
<style scoped>
.upload-parent {
  padding: 24px 50px;
}
.upload-btn {
  height: 38px;
  border-radius: 6px;
  margin-top: 30px;
  color: var(--button-text-color);
  background-color: var(--button-bg-color);
  border-color: var(--button-bg-color);
  /* margin-bottom: 20px; */
}

.upload-txt {
  color: var(--txt-color);
}

::v-deep .el-upload-dragger {
  /* padding-bottom: 80px; */
  background: var(--menu-background);
  border: 1px dashed var(--item-border);
}
::v-deep .el-upload-dragger:hover {
  border-color: var(--active-border);
}
.table-content {
  height: 253px;
  border: 1px solid var(--item-border);
  border-radius: 10px;
  overflow: hidden;
  background: var(--menu-background);
}
.table-content ::v-deep .el-icon {
  color: var(--primary);
}
.file-total {
  font-weight: bold;
  float: left;
  line-height: 32px;
  color: var(--txt-color);
  /* margin-bottom: 14px; */
}
.file-operate {
  float: right;
  margin-bottom: 10px;
  position: relative;
}
.operate-btn {
  padding: 8px;
  border-radius: 10px;
  /* box-shadow: 0 0px 5px #ccc; */
}
.operate-btn:hover {
  color: var(--primary);
}
.submit-btn {
  color: var(--button-text-color);
  background-color: var(--button-bg-color);
  border-color: var(--button-bg-color);
}
.upload-btn:hover, .submit-btn:hover {
  color: var(--button-text-color);
  background-color: var(--button-hover-bg-color);
  border-color: var(--button-hover-border-color);
}
.model-select {
  width: 112px;
  margin: 0 12px;
  border-radius: 10px;
  /* box-shadow: 0 1px 5px #ccc; */
}
::v-deep .el-select__wrapper {
  border-radius: 10px;
}
.upload-table {
  position: absolute;
  left: -105px;
}
.reading-page {
  width: 672px;
  padding: 24px;
  border: 1px solid var(--border);
  border-radius: 20px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}
::v-deep .el-table, ::v-deep .el-table tr, ::v-deep .el-table th.el-table__cell {
  background: transparent;
}
::v-deep .el-table--enable-row-hover .el-table__body tr:hover>td.el-table__cell {
  background: var(--menu-background-all);
}
::v-deep .el-table td.el-table__cell, ::v-deep .el-table th.el-table__cell.is-leaf {
  border-bottom: 1px solid var(--border);
  color: var(--txt-color);
}
::v-deep .el-table--border .el-table__inner-wrapper:after, ::v-deep .el-table--border:after, ::v-deep .el-table--border:before, ::v-deep .el-table__inner-wrapper:before {
  background-color: var(--border);
}
::v-deep .el-select-dropdown__item.is-selected {
  color: var(--primary);
}
::v-deep .el-loading-mask {
  background: var(--menu-background-all);
}
</style>
